<template>
  <div>
    <el-card v-loading="loading">
      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" class="mb-[20px]">
        <div class="flex flex-wrap gap-4">
          <el-form-item label="路由路径" class="!mb-4">
            <el-input
              v-model="queryForm.path"
              placeholder="请输入路由路径"
              clearable
              class="!w-[200px]"
            />
          </el-form-item>
          <el-form-item label="路由名称" class="!mb-4">
            <el-input
              v-model="queryForm.name"
              placeholder="请输入路由名称"
              clearable
              class="!w-[200px]"
            />
          </el-form-item>
          <el-form-item label="页面标题" class="!mb-4">
            <el-input
              v-model="queryForm.title"
              placeholder="请输入页面标题"
              clearable
              class="!w-[200px]"
            />
          </el-form-item>
        </div>

        <div
          class="flex items-center justify-between w-full mt-4 border-t pt-4"
        >
          <div class="flex gap-2">
            <el-button type="primary" @click="handleQuery">
              <el-icon class="mr-2"><Search /></el-icon>查询
            </el-button>
            <el-button @click="resetForm">
              <el-icon class="mr-2"><Refresh /></el-icon>重置
            </el-button>
          </div>
        </div>
      </el-form>

      <!-- 表格部分 -->
      <PureTable
        row-key="path"
        :data="routeList"
        :columns="columns"
        :height="630"
        border
        :header-cell-style="{
          background: 'var(--el-fill-color-light)',
          color: 'var(--el-text-color-primary)'
        }"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
          checkStrictly: false
        }"
        default-expand-all
      />

      <!-- 编辑抽屉 -->
      <el-drawer
        v-model="drawerVisible"
        title="编辑路由配置"
        size="40%"
        :destroy-on-close="true"
      >
        <el-form
          v-if="currentRoute"
          ref="formRef"
          :model="currentRoute"
          label-width="100px"
          class="p-[20px]"
        >
          <el-form-item label="页面标题" prop="meta.title" required>
            <el-input
              v-model="currentRoute.meta.title"
              placeholder="请输入页面标题"
            />
          </el-form-item>

          <el-form-item label="父级ID" prop="pid">
            <el-input-number
              v-model="currentRoute.pid"
              :min="-1"
              placeholder="请输入父级ID，-1表示顶级路由"
              class="!w-[200px]"
            />
            <div class="text-gray-400 text-sm mt-1">
              -1表示顶级路由，其他值表示父路由的ID
            </div>
          </el-form-item>

          <el-form-item label="排序" prop="meta.rank" required>
            <el-input-number
              v-model="currentRoute.meta.rank"
              :min="0"
              placeholder="数字越小越靠前"
              class="!w-[200px]"
            />
            <div class="text-gray-400 text-sm mt-1">数字越小菜单排序越靠前</div>
          </el-form-item>

          <el-form-item label="角色" prop="meta.roles">
            <el-select
              v-model="currentRoute.meta.roles"
              multiple
              placeholder="请选择角色"
              class="w-full"
            >
              <el-option
                v-for="role in roleList"
                :key="role.id"
                :label="role.name"
                :value="role.name"
              />
            </el-select>
            <div class="text-gray-400 text-sm mt-1">
              可以选择多个角色，只有拥有对应角色的用户才能访问
            </div>
          </el-form-item>

          <div class="flex justify-end gap-2 mt-4">
            <el-button @click="drawerVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
          </div>
        </el-form>
      </el-drawer>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h, onMounted } from "vue";
import { Search, Edit, Refresh } from "@element-plus/icons-vue";
import { ElButton, ElIcon, ElMessage, ElTag } from "element-plus";
import JsonEditor from "@/components/JsonEditor/index.vue";
import { getAllRoles, getRouterByPage, setRouter } from "@/api/index";

// 加载状态
const loading = ref(false);

// 查询表单
const queryForm = reactive({
  path: "", // 路由路径
  name: "", // 路由名称
  title: "" // 页面标题
});

// 默认的按钮权限选项
const defaultAuths = [
  "permission:btn:add",
  "permission:btn:edit",
  "permission:btn:delete",
  "permission:btn:view"
];

// 编辑抽屉
const drawerVisible = ref(false);
const currentRoute = ref<any>(null);
const formRef = ref();

// 路由数据
const routeList = ref([]);

// 角色列表
const roleList = ref([]);

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await getAllRoles();
    if (res.status === "success" && res.data) {
      roleList.value = res.data;
    }
  } catch (error) {
    console.error("获取角色列表失败:", error);
  }
};

// 获取路由数据
const fetchRouteData = async () => {
  loading.value = true;
  try {
    const res = await getRouterByPage({
      page: 1,
      size: 100
    });
    if (res.status === "success" && res.data?.records) {
      try {
        routeList.value = res.data.records.map(route => ({
          ...route.component,
          id: route.id,
          pid: route.pid,
          meta: route.component.meta,
          roles: route.roles,
          children: route.component.children?.map(child => ({
            ...child,
            id: route.id,
            pid: route.pid,
            parentMeta: route.component.meta,
            roles: route.roles
          }))
        }));
      } catch (parseError) {
        ElMessage.error("路由数据解析错误");
        console.error("路由数据解析错误:", parseError);
      }
    } else {
      ElMessage.error("获取路由数据失败");
    }
  } catch (error) {
    ElMessage.error("获取路由数据失败");
    console.error("请求错误:", error);
  } finally {
    loading.value = false;
  }
};

// 在组件挂载时获取数据
onMounted(() => {
  fetchRouteData();
  fetchRoles();
});

// 表格列配置
const columns = [
  {
    label: "路由路径",
    prop: "path",
    width: 280,
    align: "center",
    cellRenderer: ({ row }) => {
      return h(
        ElTag,
        {
          type: "success",
          effect: "plain",
          class: "path-cell"
        },
        { default: () => row.path }
      );
    }
  },
  {
    label: "路由名称",
    prop: "name",
    width: 180,
    align: "center",
    cellRenderer: ({ row }) => {
      return h("span", { class: "title-cell" }, row.name || "-");
    }
  },
  {
    label: "组件路径",
    prop: "component",
    width: 280,
    align: "center",
    cellRenderer: ({ row }) => {
      return h("span", { class: "component-cell" }, row.component || "-");
    }
  },
  {
    label: "页面标题",
    prop: "meta.title",
    width: 180,
    align: "center",
    cellRenderer: ({ row }) => {
      return h("span", { class: "title-cell" }, row.meta?.title || "-");
    }
  },
  {
    label: "排序",
    prop: "parentMeta.rank",
    sortable: true,
    width: 100,
    align: "center",
    cellRenderer: ({ row }) => {
      return h("span", { class: "rank-cell" }, row.parentMeta?.rank ?? "-");
    }
  },
  {
    label: "pid",
    prop: "pid",
    sortable: true,
    width: 100,
    align: "center",
    cellRenderer: ({ row }) => {
      return h("span", { class: "rank-cell" }, row.pid ?? "-");
    }
  },
  {
    label: "角色",
    prop: "meta.roles",
    minWidth: 300,
    align: "center",
    cellRenderer: ({ row }) => {
      if (!row.meta?.roles?.length) return h("span", "-");
      return h(
        "div",
        {
          class: "roles-cell flex flex-wrap gap-1 justify-center items-center"
        },
        row.meta.roles.map(role =>
          h(
            ElTag,
            {
              size: "small",
              type: "info",
              class: "m-1"
            },
            { default: () => role }
          )
        )
      );
    }
  },
  {
    label: "操作",
    width: 100,
    fixed: "right",
    align: "center",
    cellRenderer: ({ row }) => {
      return h(
        ElButton,
        {
          type: "primary",
          link: true,
          onClick: () => handleEdit(row)
        },
        {
          default: () => [
            h(
              ElIcon,
              { class: "mr-1" },
              {
                default: () => h(Edit)
              }
            ),
            "编辑"
          ]
        }
      );
    }
  }
];

// 重置表单
const resetForm = () => {
  queryForm.path = "";
  queryForm.name = "";
  queryForm.title = "";
  fetchRouteData();
};

// 查询方法
const handleQuery = () => {
  // 过滤数据
  let filteredData = JSON.parse(JSON.stringify(routeList.value));

  const filterRoute = routes => {
    return routes.filter(route => {
      let match = true;
      if (queryForm.path && !route.path.includes(queryForm.path)) {
        match = false;
      }
      if (
        queryForm.name &&
        route.name &&
        !route.name.includes(queryForm.name)
      ) {
        match = false;
      }
      if (
        queryForm.title &&
        route.meta?.title &&
        !route.meta.title.includes(queryForm.title)
      ) {
        match = false;
      }

      if (route.children) {
        route.children = filterRoute(route.children);
        if (route.children.length > 0) {
          match = true;
        }
      }

      return match;
    });
  };

  routeList.value = filterRoute(filteredData);
};

// 编辑路由
const handleEdit = row => {
  // 深拷贝对象，避免直接修改原数据
  currentRoute.value = JSON.parse(JSON.stringify(row));
  // 确保 meta 对象存在
  if (!currentRoute.value.meta) {
    currentRoute.value.meta = {};
  }
  // 确保数组字段存在
  if (!currentRoute.value.meta.roles) {
    currentRoute.value.meta.roles = [];
  }
  // 从父路由获取排序值
  if (currentRoute.value.parentMeta?.rank !== undefined) {
    currentRoute.value.meta.rank = currentRoute.value.parentMeta.rank;
  } else if (typeof currentRoute.value.meta.rank !== "number") {
    currentRoute.value.meta.rank = 0;
  }
  drawerVisible.value = true;
};

// 保存路由配置
const handleSave = async () => {
  try {
    const res = await getRouterByPage({
      page: 1,
      size: 100
    });
    if (res.status !== "success" || !res.data?.records) {
      throw new Error("获取原始路由数据失败");
    }

    const records = res.data.records;
    let targetRoute = null;

    // 查找要更新的路由记录
    records.forEach(route => {
      if (route.id === currentRoute.value.id) {
        targetRoute = route;
      }
    });

    if (!targetRoute) {
      throw new Error("未找到要更新的路由记录");
    }

    // 获取选中角色对应的角色ID
    const selectedRoleIds = roleList.value
      .filter(role => currentRoute.value.meta.roles.includes(role.name))
      .map(role => role.id);

    // 构建请求参数
    const params = {
      router_id: targetRoute.id,
      role_ids: selectedRoleIds,
      pid: currentRoute.value.pid,
      component: {
        ...targetRoute.component,
        meta: {
          ...targetRoute.component.meta,
          rank: currentRoute.value.meta.rank,
          title: currentRoute.value.meta.title
        }
      }
    };

    // 如果有 children，则处理 children
    if (targetRoute.component.children) {
      params.component.children = targetRoute.component.children.map(child => {
        if (child.path === currentRoute.value.path) {
          return {
            ...child,
            meta: {
              ...child.meta,
              title: currentRoute.value.meta.title
            }
          };
        }
        return child;
      });
    }

    // 调用更新接口
    await setRouter(params);

    drawerVisible.value = false;
    ElMessage.success("保存成功");
    fetchRouteData();
  } catch (error) {
    ElMessage.error(error.message || "保存失败");
    console.error("保存错误:", error);
  }
};
</script>

<style lang="scss" scoped>
:deep(.el-drawer__body) {
  padding: 20px;
}

:deep(.el-table) {
  // 表格基础样式
  .cell {
    padding: 8px 0;
    line-height: 1;

    // 标题列
    .title-cell {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }

    // 排序列
    .rank-cell {
      font-weight: 500;
      color: var(--el-text-color-secondary);
    }

    // 角色列
    .roles-cell {
      .el-tag {
        margin: 2px;
      }
    }

    // 操作列按钮
    .el-button {
      padding: 4px 8px;

      &:hover {
        color: var(--el-color-primary) !important;
        background-color: var(--el-color-primary-light-9);
      }
    }
  }

  // 表头样式
  .el-table__header {
    th {
      height: 50px;
      font-weight: bold;
      color: var(--el-text-color-primary);
      background-color: var(--el-fill-color-light);
    }
  }

  // 表格行样式
  .el-table__row {
    &:hover {
      background-color: var(--el-fill-color-lighter) !important;
    }

    td {
      padding: 12px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
    }
  }
}
</style>
